//
//  WYJHomeViewModel.swift
//  MySinaWeibo
//
//  Created by eastriver on 16/10/15.
//  Copyright © 2016年 believewilliam. All rights reserved.
//

import UIKit
import SDWebImage
class WYJHomeViewModel: NSObject {
//    // 模型对象属性
//    var statusModel: WYJStatusModel?
//    // 模型数组
//    lazy var statusModelArray = [WYJStatusModel]()
    // 微博的视图模型数组
    lazy var statusViewModelArray: [WYJStatusViewModel] = [WYJStatusViewModel]()
    
    func loadData(isPullUp: Bool, finished: @escaping (Bool, Int) -> ()) {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        var parameters = ["access_token": WYJUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token ?? ""]
        // 判断是否是上拉加载更多
        if isPullUp == true {
            parameters["max_id"] = "\((statusViewModelArray.last?.statusModel?.id ?? 0) - 1 )"
        } else {
            // 下拉刷新和首次加载数据
            parameters["since_id"] = "\(statusViewModelArray.first?.statusModel?.id ?? 0)"
        }
        
        WYJNetworkTool.sharedTool.request(method: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
            if error != nil {
                finished(false, 0)
                return
            }
            let dict = responseObject as! [String: Any]
            let statusArray = dict["statuses"] as! [[String: Any]]
            // 遍历数组，字典转模型
            var tempArray = [WYJStatusViewModel]()
            // 使用调度组
            let group = DispatchGroup()
            for item in statusArray {
                //                let model = WYJStatusModel(dict: item)
                let viewModel = WYJStatusViewModel()
                let model = WYJStatusModel()
                model.yy_modelSet(with: item)
                viewModel.statusModel = model
                tempArray.append(viewModel)
                // 判断该viewModel对应的cell配图是否只有一张，如果是，把该图片下载下来。此处应该用viewModel，而不是model，这样就可以避免还要判断是转发微博还是原创微博的配图数组。
                if viewModel.pictureArray?.count == 1 {
                    let url = URL(string: viewModel.pictureArray?.first?.wap_pic ?? "")
                    // 向group中加1
                    group.enter()
                    // 下载图片
                    SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, error, _, _, _) in
                        if error == nil {
                            // 向group中减1
                            group.leave()
//                            print(url)
//                            print(">>>>>>>>")
                        }
                    })
                  
            }
            }
            if isPullUp == true {
                self.statusViewModelArray += tempArray
            } else {
                self.statusViewModelArray = tempArray + self.statusViewModelArray
            }
            // 当group中值为0时，调用finished闭包
                group.notify(queue: DispatchQueue.main, execute: {
                    finished(true, tempArray.count)
//                    print("所有的单张图片都下载完了")
                })
        }
    }

}
